package com.uobgroup.ews.uam.web;

import com.uobgroup.ews.uam.core.dao.ldap.LDSDaoImpl;
import com.uobgroup.ews.uam.core.domain.Segment;
import com.uobgroup.ews.uam.core.model.Group;
import com.uobgroup.ews.uam.core.service.ReferenceService;
import com.uobgroup.ews.uam.core.service.SecurityGroupService;
import com.uobgroup.ews.uam.core.service.ldap.LDSServiceImpl;

import java.io.UnsupportedEncodingException;
import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/segments")
@Controller
public class SegmentController {

   @Autowired
   private ReferenceService referenceService;

   @Autowired
   private SecurityGroupService securityGroupService;
   
   @Autowired
   private LDSServiceImpl lDsService;
   
   @Autowired
   private ReloadableResourceBundleMessageSource messageSource;

   @RequestMapping(method = RequestMethod.POST, produces = "text/html")
   public String create(@Valid Segment segment, BindingResult bindingResult, Model uiModel,
         HttpServletRequest httpServletRequest, Principal principal) {
      Group group = lDsService.findGroupByBaseDN(segment.getSegmentReference().getName().trim(), LDSDaoImpl.LDAP_DN_GROUP_SEGMENT);
      if (null != group) {
         uiModel.addAttribute("messageError", messageSource.getMessage("exist_security_group_in_lds", new String[] {messageSource.getMessage("label_com_uobgroup_ews_uam_core_domain_segment", null,null)}, null));
      }
      if (bindingResult.hasErrors() || null != group) {
         populateEditForm(uiModel, segment);
         return "segments/create";
      }
      uiModel.asMap().clear();
      segment.setLastModificationUserId(principal.getName());
      referenceService.saveSegment(segment);
      return "redirect:/segments/" + encodeUrlPathSegment(segment.getId().toString(), httpServletRequest);
   }

   @RequestMapping(value = "/create", produces = "text/html")
   public String createForm(Model uiModel) {
      populateEditForm(uiModel, new Segment());
      return "segments/create";
   }

   @RequestMapping(value = "/{id}", produces = "text/html")
   public String show(@PathVariable("id") Long id, Model uiModel) {
      uiModel.addAttribute("segment", referenceService.findSegment(id));
      uiModel.addAttribute("itemId", id);
      return "segments/show";
   }

   @RequestMapping(produces = "text/html")
   public String list(@RequestParam(value = "page", required = false) Integer page,
         @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
      if (page != null || size != null) {
         int sizeNo = size == null ? 10 : size.intValue();
         final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
         uiModel.addAttribute("segments", referenceService.findSegmentEntries(firstResult, sizeNo));
         float nrOfPages = (float) referenceService.countSegments() / sizeNo;
         uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
               : nrOfPages));
      }
      else {
         uiModel.addAttribute("segments", referenceService.findAllSegments());
      }
      return "segments/list";
   }

   @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
   public String update(@Valid Segment segment, BindingResult bindingResult, Model uiModel,
         HttpServletRequest httpServletRequest) {
      if (bindingResult.hasErrors()) {
         populateEditForm(uiModel, segment);
         return "segments/update";
      }
      uiModel.asMap().clear();
      referenceService.updateSegment(segment);
      return "redirect:/segments/" + encodeUrlPathSegment(segment.getId().toString(), httpServletRequest);
   }

   @RequestMapping(value = "/update/{id}", produces = "text/html")
   public String updateForm(@PathVariable("id") Long id, Model uiModel) {
      populateEditForm(uiModel, referenceService.findSegment(id));
      return "segments/update";
   }

   @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
   public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
         @RequestParam(value = "size", required = false) Integer size, Model uiModel, Principal principal) {
      Segment segment = referenceService.findSegment(id);
      segment.setLastModificationUserId(principal.getName());
      referenceService.remove(segment);
      uiModel.asMap().clear();
      uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
      uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
      return "redirect:/segments";
   }

   void populateEditForm(Model uiModel, Segment segment) {
      uiModel.addAttribute("segment", segment);
      uiModel.addAttribute("references", referenceService.findAllReferencesThatHasNoSegment());
      uiModel.addAttribute("securitygroups", securityGroupService.findAllSecurityGroupsThatHasNoSegment());
   }

   String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
      String enc = httpServletRequest.getCharacterEncoding();
      if (enc == null) {
         enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
      }
      try {
         pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
      }
      catch (UnsupportedEncodingException uee) {
      }
      return pathSegment;
   }
}
